package com.wlq.demo;

import cn.hutool.core.date.DateTime;
import com.wlq.demo.uitls.RedisHelper;
import org.freehep.graphicsio.emf.EMFExportFileType;
import org.freehep.graphicsio.emf.EMFInputStream;
import org.freehep.graphicsio.emf.EMFPanel;
import org.freehep.graphicsio.emf.EMFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author csb
 * @description: TODO
 * @date 2024/4/22 10:48
 */

public class bigFileUpload {

    private static final String CHUNK_PREFIX = "big_file:";
    private static Long CHUNK_SIZE = 1024 * 1024L;
    private static final String remoteRootPath = "D:\\test\\big_file";

    @Autowired
    private RedisHelper redisHelper;

//    public static void main(String[] args) {
//        File file = new File("");
//        upload(file,1,"wlq","test");
//    }

    private boolean upload(MultipartFile file, Integer chunkIndex, String md5, Long totalFileSize, String fileName) throws IOException {
        //创建存放文件夹
        String date = DateTime.now().toString("yyyyMMdd");
        File dirFile = new File(remoteRootPath + "/"+date);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //分区文件
        String relativeFilePath = remoteRootPath + "/"+date + fileName;
        File tempFile = new File(relativeFilePath);
        RandomAccessFile rw = new RandomAccessFile(tempFile, "rw");
        //定位到分片的偏移量
        rw.seek(CHUNK_SIZE * chunkIndex);
        //写入分片数据
        rw.write(file.getBytes());
        //关闭流
        rw.close();
        //读取已经分片的集合
        List<Object> hasChunkList;
        String hasChunkKey = CHUNK_PREFIX + md5;
        if (redisHelper.hasKey(hasChunkKey)){
            hasChunkList = redisHelper.lrange(hasChunkKey);
        }else {
            hasChunkList = new ArrayList<>();
        }
        hasChunkList.add(chunkIndex);
        //最新分片下标跟新到redis
        redisHelper.set(hasChunkKey,chunkIndex);
        //判断上传是否完成
        int totalNeedChunks = (int) Math.ceil(totalFileSize / CHUNK_SIZE);
        //判断是否上传完成，总共需要的分片数 和 已经上传分片数相等
        boolean isOk = totalNeedChunks == hasChunkList.size();
        if (isOk){
            return true;
        }else {
            return false;
        }
    }

//    public static void uploadFileInChunks(String uploadUrl, File file, int chunkSize) throws IOException {
//        int totalChunks = (int) Math.ceil((double) file.length() / chunkSize);
//
//        for (int i = 0; i < totalChunks; i++) {
//            int start = i * chunkSize;
//            int length = Math.min(chunkSize, (int) (file.length() - start));
//            File chunk = createFileChunk(file, start, length);
//
//            // 上传分片到服务器
//            uploadChunk(uploadUrl, i, chunk);
//
//            // 删除本地分片文件
//            chunk.delete();
//        }
//    }
//
//    private static File createFileChunk(File file, int start, int length) throws IOException {
//        byte[] buffer = new byte[length];
//        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
//             FileOutputStream fileOutputStream = new FileOutputStream("chunk_" + start + ".part")) {
//            randomAccessFile.seek(start);
//            randomAccessFile.read(buffer);
//            fileOutputStream.write(buffer);
//        }
//        return new File("chunk_" + start + ".part");
//    }
//
//    private static void uploadChunk(String uploadUrl, int chunkNumber, File chunkFile) throws IOException {
//        try (InputStream fileInputStream = new FileInputStream(chunkFile);
//             HttpURLConnection connection = (HttpURLConnection) new URL(uploadUrl + "?chunk=" + chunkNumber).openConnection()) {
//            connection.setDoOutput(true);
//            connection.setRequestMethod("POST");
//            OutputStream out = connection.getOutputStream();
//            byte[] buffer = new byte[4096];
//            int bytesRead;
//            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
//                out.write(buffer, 0, bytesRead);
//            }
//            out.flush();
//            // 检查服务器响应代码以确认上传成功
//            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
//                throw new IOException("Upload failed, HTTP response code: " + connection.getResponseCode());
//            }
//        }
//    }
//
//    public static void main(String[] args) {
//        try {
//            String uploadUrl = "http://yourserver.com/upload"; // 替换为你的上传URL
//            File file = new File("largefile.bin"); // 替换为你要上传的文件
//            int chunkSize = 1024 * 1024; // 分片大小为1MB
//            uploadFileInChunks(uploadUrl, file, chunkSize);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
